package contrl

import (
	"core/env"
	"core/mysql"
	"core/utils"
	"db/stat"
	"github.com/gin-gonic/gin"
	"math"
	"time"
)

type StatContrl struct{}

type StatListInfo struct {
	TableName string
	Keys      []string
	Values    []int
}

type StatListRes struct {
	List []StatListInfo
}

// 图片列表
func (*StatContrl) List(c *gin.Context) (res interface{}, e Error) {
	resList := make([]StatListInfo, 0)

	limit := GetInt(c, "limit")
	if limit == 0 {
		limit = 30
	}
	list, err := stat.FindStatList(limit)
	if err != nil {
		return nil, GenError(err)
	}

	for _, info := range stat.Menus {
		thisList, found := list[info.Type]
		if !found {
			utils.Error("not found info in list")
			continue
		}
		for _, query := range info.QueryInfo {
			item := StatListInfo{
				TableName: query.Key,
				Keys:      make([]string, 0),
				Values:    make([]int, 0),
			}
			for _, data := range thisList {
				item.Keys = append(item.Keys, stat.GenWeekDay(data.StatDate))
				switch query.ValueType {
				case stat.Cardinality:
					item.Values = append(item.Values, data.StatCardinality)
				case stat.Count:
					item.Values = append(item.Values, data.StatCount)
				case stat.Mean:
					item.Values = append(item.Values, int(data.StatMean))
				}
			}
			resList = append(resList, item)
		}
	}

	res = StatListRes{
		List: resList,
	}
	return
}

func (*StatContrl) Collect(c *gin.Context) (res interface{}, e Error) {
	day := GetInt(c, "day")
	if day < 1 || day > 120 {
		return nil, GenErrorMsg("day 参数错误")
	}
	res = "ok"
	go utils.SafeGo(func() {
		now := time.Now()
		boundAt := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
		list := make([]*stat.Stat, 0)
		for _, info := range stat.Menus {
			for i := 1; i <= day; i++ {
				from := boundAt.AddDate(0, 0, -i)
				statData := &stat.Stat{StatType: info.Type, StatDate: stat.GenDate(from)}
				exist, err := mysql.X.Exist(statData)
				if err != nil {
					utils.Error(err)
				}
				if !exist {
					res, err := stat.RequestGraylogAPI(
						env.Conf.GraylogIp+":9000",
						info.Field,
						info.Query,
						from,
						boundAt.AddDate(0, 0, -i+1),
					)
					if err != nil {
						utils.Error(err)
					}
					statData.StatMean = math.Max(res.Mean, 0)
					statData.StatCount = utils.Max(res.Count, 0)
					statData.StatCardinality = utils.Max(res.Cardinality, 0)
					err = mysql.Create(statData)
					if err != nil {
						utils.Error(err)
					}
				}
				utils.Info(info.Type, statData.StatDate, statData)
				list = append(list, statData)
			}
		}
	})
	return
}
